package com.apps.java.反射_操作注解;

import java.lang.annotation.*;
import java.lang.reflect.Field;

/*
    案例：反射操作注解：ORM
    要求：利用注解和反射完成类和表结构的映射关系
 */
public class TestDemo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {

        //获取Student的Class对象
        Class<?> c1 = Class.forName("com.apps.java.反射_操作注解.Student");

        //通过反射获得注解
        System.out.println("通过反射获得注解：");
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        System.out.println("--------------------");

        //获得注解的value的值
        System.out.println("获得注解中的value值");
        Table table = c1.getAnnotation(Table.class);
        System.out.println(table.value());

        //获得类指定的注解
        System.out.println("获得类指定的注解：");
        Field name = c1.getDeclaredField("id");
        TableField annotation = name.getAnnotation(TableField.class);
        System.out.println(annotation.columnName() +"," + annotation.Type() +"," + annotation.length());


    }
}

//学生类
@Table(value = "db_student")
class Student {

    @TableField(columnName = "db_id",Type = "int",length = 10)
    private int id;
    @TableField(columnName = "db_name",Type = "int",length = 10)
    private String name;
    @TableField(columnName = "db_id",Type = "varchar",length = 5)
    private int age;

    public Student() {
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table{
    String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface TableField{
    String columnName();
    String Type();
    int length();
}